import Taro from "@tarojs/taro";

export const $Req = (ob) => {
  const header = {
    'content-type': 'application/json'
  };
  const token = Taro.getStorageSync('token');
  if (token.length) {
    header.Authorization = token;
  }

  return Taro.request({
    url: `https://www.baitongsc.com${ob.url}`,
    data: {
      ...ob.data
    },
    header,
    method: ob.type.toUpperCase()
  }).then(res => {
    res = res.data;
    if (res.code === 200 || res.success) {

      if (ob.url != "/user/getWxPhoneNum" && Taro.getStorageSync("userInfo")) {
        if (!Taro.getStorageSync('userPhone')) {
          Taro.redirectTo({
            url: "/pages/index/regist"
          })
          return false;
        }
      }

      return res;
    } else {
      // 强制登录才能查看，这也取决于接口
      if (res.code == 10002) {
        Taro.removeStorageSync("token");
        Taro.removeStorageSync("userInfo");
        Taro.removeStorageSync("userPhone");

        // Taro.redirectTo({
        //   url: "/pages/index/welcome"
        // })
        return false;
      }


      Taro.showToast({
        title: res.msg,
        icon: 'none',
        mask: true,
      });
      
      return {
        code: res.code,
        message: res.msg,
        data: null
      }
    }
  })
}

export const fileRequest = (options) => Taro.uploadFile({
  url: `https://www.baitongsc.com${options.url}`,
  header: { "Content-Type": "multipart/form-data", 'Authorization': Taro.getStorageSync('token') },
  name: 'file',
  filePath: options.data
}).then(res => res);